package service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import model.Tvip;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import dao.VipDaoI;
import pageModel.DataGrid;
import pageModel.Vip;
import service.VipServiceI;
@Service("vipService")
public class VipServiceImpl implements VipServiceI{
private VipDaoI vipDao;

	public VipDaoI getVipDao() {
	return vipDao;
}
@Autowired
public void setVipDao(VipDaoI vipDao) {
	this.vipDao = vipDao;
}

	@Override
	public Vip save(Vip vip) {
		   Tvip tv=new Tvip();
		   BeanUtils.copyProperties(vip,tv);
		   tv.setId(UUID.randomUUID().toString());
		   tv.setCreatedatetime(new Date()); 
		   vipDao.save(tv);
		   BeanUtils.copyProperties(tv, vip);
		   return vip;
	}

	@Override
	public DataGrid datagrid(Vip vip) {
		DataGrid dg=new DataGrid();
		String hql="from Tvip t where 1=1";
		Map<String,Object> params=new HashMap<String,Object>();
		hql = addWhere(vip, hql, params);
		String totalHql="select count(*) "+hql;
		if(vip.getSort()!=null){
		hql+=" order by "+vip.getSort()+" "+vip.getOrder();
		}
		List<Tvip> su=vipDao.find(hql,params,vip.getPage(),vip.getRows());
		List<Vip> l=new ArrayList<Vip>();
		if(su!=null&&su.size()>0){
			for( Tvip t :su){
				Vip v=new Vip();
				BeanUtils.copyProperties(t, v);
				l.add(v);
			}
		}
		dg.setTotal(vipDao.count(totalHql,params));
		dg.setRows(l);
		return dg;
	}
	private String addWhere(Vip vip, String hql, Map<String, Object> params) {
		if(vip.getTelephone()!=null&&!vip.getTelephone().trim().equals("")){
		hql+=" and t.telephone like :telephone";
		params.put("telephone", "%%"+vip.getTelephone()+"%%");
		}
		if(vip.getCardid()!=null&&!vip.getCardid().trim().equals("")){
			hql+=" and t.cardid like :cardid";
			params.put("cardid", "%%"+vip.getCardid()+"%%");
			}
		if(vip.getName()!=null&&!vip.getName().trim().equals("")){
			hql+=" and t.name like :name";
			params.put("name", "%%"+vip.getName()+"%%");
			}
		if (vip.getCreatedatetimeStart() != null) {
			hql += " and t.createdatetime >= :createdatetimeStart";
			params.put("createdatetimeStart", vip.getCreatedatetimeStart());
		}
		if (vip.getCreatedatetimeEnd() != null) {
			hql += " and t.createdatetime <= :createdatetimeEnd";
			params.put("createdatetimeEnd", vip.getCreatedatetimeEnd());
		}
		return hql;
	}

	@Override
	public void remove(String ids) {
		String [] nids=ids.split(",");
		String hql="delete Tvip t where t.id in(";
		for(int i=0;i<nids.length;i++){
			if(i>0){
				hql+=",";
			}
			hql+="'"+nids[i]+"'";
		}
		hql+=")";
		vipDao.executeHql(hql);
	}

	@Override
	public void edit(Vip vip) {
		Tvip t=vipDao.get(Tvip.class, vip.getId());
		vip.setUpdatedatetime(new Date());
	    BeanUtils.copyProperties(vip, t);
	}

}
